<template>
  <div class="container" id="messageList" v-loading="loadingVisible">
    <image-viewer ref="imageViewer" :image-url="image.url" :image-width="image.width" :image-height="image.height"></image-viewer>
    <div v-if="hasMoreMessage" class="load-more-message"><span @click="getMessageList(true)">加载更多消息</span></div>
    <div :id="'message_' + item.msgId" v-for="(item, index) in this.messageList" :key="item.msgId">
      <div class="message-container">
        <div class="message">
          <!-- <div class="status-wrapper" :class="{'sysuser-status-wrapper': item.sendUserid === '00000000000000000000000000000000'}"> -->
          <div  :class="[{'sysuser-status-wrapper': item.sendUserid === '00000000000000000000000000000000'},{'status-wrapper-right': userInfo.userid == item.sendUserid, 'status-wrapper': userInfo.userid !== item.sendUserid}]">
            <div v-if="item.senderRealAvatarUrl" style="width: 32px; height:32px;"><img class="status-wrapper-image" :src="getAvatarUrl(item)" /></div>
            <template v-else>{{ item.sendUsername }}</template>
            <div v-if="item.sendUserid != '00000000000000000000000000000000'" class="online-status-container">
              <status-online-avatar v-if="item.senderOnlineStatus === 'online'"></status-online-avatar>
              <status-away-avatar v-else-if="item.senderOnlineStatus === 'away'"></status-away-avatar>
              <status-offline-avatar v-else-if="item.senderOnlineStatus === 'offline'"></status-offline-avatar>
              <status-dnd-avatar v-else-if="item.senderOnlineStatus === 'dnd'"></status-dnd-avatar>
            </div>
          </div>
          <div class="message-content" :class="{ 'message-content-myself': userInfo.userid == item.sendUserid }">
            <div class="info-box">
              <!-- <span class="sender">{{ item.sendUsername ? item.sendUsername : item.sendUsername }}</span> -->
              <span :class="[{'sender-right': userInfo.userid == item.sendUserid, 'sender': userInfo.userid !== item.sendUserid}]">{{ item.sendUsername ? item.sendUsername : item.sendUsername }}</span>
              <!-- <span class="createAt">{{ getCreateDateTime(item) + (item.msgType=='prichat'?item.msgStateDesc:'')}}</span> -->
              <span :class="[{'createAt-right': userInfo.userid == item.sendUserid, 'createAt': userInfo.userid !== item.sendUserid}]">{{ getCreateDateTime(item) + (item.msgType=='prichat'?(item.msgStateDesc?item.msgStateDesc:''):'')}}</span>
              <span v-if="userInfo.userid == item.sendUserid" class="delete-message" @click="removeMessage(item, index)">回撤</span>
            </div>
            <!-- <div v-if="((!item.sendObject)||item.sendObject==''||item.sendObject==null)&&item.sendContent" :class="[{'content-select': userInfo.userid == item.sendUserid, 'content': userInfo.userid !== item.sendUserid}, {'system-content': item.type}]" v-html="item.sendContent"></div> -->
            <div v-if="((!item.sendObject)||item.sendObject==''||item.sendObject==null)&&item.sendContent" :class="[{'content-right': userInfo.userid == item.sendUserid, 'content': userInfo.userid !== item.sendUserid}, {'system-content': item.type}]" v-html="item.sendContent"></div>
            <template v-else>
              <div v-if="item.sendObject=='U'">
                <a :href="getFileUrl(item)" target="_blank">
                  {{item.sendContent.title+" "+getFileUrl(item)}}
                </a>
              </div>
              <div v-if="item.sendObject=='P'">
                <div >
				            <img class="emptyGif" :src="item.sendContent.imgUrl"  >
				            <span>{{item.sendContent.title}}</span>
                    <!-- <span>{{item.sendContent.imgUrl}}</span> -->
			              <span v-if="item.sendContent.minPrice!=null && item.sendContent.minPrice!=''">￥{{item.sendContent.minPrice == item.sendContent.maxPrice ? item.sendContent.minPrice : item.sendContent.minPrice+"~"+item.sendContent.maxPrice}}</span>
		            </div>
                <a :href="getFileUrl(item)" target="_blank" style="color: #1A6CDE;">
                  {{"点击跳转"}}
                  <!-- {{item.sendContent.title+" "+getFileUrl(item)}} -->
                </a>
              </div>

              <div v-else-if="isImage(item)" ><img  class="image-file" @click="viewImage(getFileUrl(item),getMessageImgWidth(item),getMessageImgHeight(item))"    :src="getFileUrl(item)"></div>
              <div v-else-if="isGif(item)" ><img  class="image-file" @click="viewImage(getFileUrl(item),getMessageImgWidth(item),getMessageImgHeight(item))"     :src="getFileUrl(item)"></div>
              <div v-else-if="item.sendObject=='F'" class="attach-file">
                <a :href="getFileUrl(item)" target="_blank">
                  <svg t="1528947448190" viewBox="0 0 1024 1024" version="1.1" width="64" height="64"> <path d="M842.72 259.904a159.04 159.04 0 0 0-113.056-46.912h-0.16a158.592 158.592 0 0 0-112.768 46.656l-0.096 0.064-294.528 294.528a95.968 95.968 0 0 0 68.128 163.712c24.512 0 49.024-9.28 67.648-27.968l294.496-294.496a31.968 31.968 0 1 0-45.248-45.248l-294.496 294.496a31.872 31.872 0 0 1-45.088-0.16 31.552 31.552 0 0 1-0.192-45.088l294.496-294.496a95.04 95.04 0 0 1 67.648-28h0.096a95.52 95.52 0 0 1 67.872 28.16c18.112 18.112 28.096 42.24 28.128 67.84a95.136 95.136 0 0 1-27.968 67.776l-79.52 79.52-0.512 0.48-220.416 220.48a160.32 160.32 0 0 1-226.432 0.096A158.912 158.912 0 0 1 224 628.224c0-42.816 16.672-83.04 46.912-113.28l300.288-300.32a31.968 31.968 0 1 0-45.248-45.248l-300.288 300.288A222.848 222.848 0 0 0 160 628.224c0 59.872 23.264 116.16 65.504 158.4a223.168 223.168 0 0 0 158.336 65.44 223.68 223.68 0 0 0 158.592-65.6l311.456-311.424a31.68 31.68 0 0 0 7.104-11.072c18.496-26.56 28.64-57.92 28.608-91.04a159.104 159.104 0 0 0-46.88-113.024" p-id="2313" fill="#616C6A"></path></svg>
                  <div class="attach-desc">
                    <div>{{ item.sendContent.title&&item.sendContent.title.length > 26 ? item.sendContent.title.substr(0, 26) + '...' : item.sendContent.title }}</div>
                    <div><i class="el-icon-download"></i>&nbsp;&nbsp;<span>{{ item.sendContent.fileExtension ? item.sendContent.fileExtension.toUpperCase() : '' }}</span>&nbsp;&nbsp;<span>{{ item.sendContent.fileSize }}KB</span></div>
                  </div>
                </a>
              </div>
            </template>
          </div>
          <div class="clear-float"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import util from '@/common/js/util';//全局公共库
import { listImGroupMessage } from '@/api/mdp/im/group/imGroupMessage'
import StatusOnlineAvatar from '@/views/mdp/im/svg/statusOnlineAvatar'
import StatusOfflineAvatar from '@/views/mdp/im/svg/statusOfflineAvatar'
import StatusDndAvatar from '@/views/mdp/im/svg/statusDndAvatar'
import StatusAwayAvatar from '@/views/mdp/im/svg/statusAwayAvatar'
import { mapGetters } from 'vuex'

import seq from '@/common/js/sequence';//全局公共库

export default {
  computed: {
    ...mapGetters([
      'userInfo','token'
    ]),
    'hasMoreMessage':function(){
      return this.pageInfo.total>this.pageInfo.pageSize*this.pageInfo.pageNum
    }
  },
  name: "message-list",
  props: ['groupId', 'channelGroup'],
  data() {
    return {  
      loadingVisible: false,
      messageList: [],
      isLoadMore: false,
      messageRemoved: false,
      image: {
        url: '',
        width: 0,
        height: 0
      }, 
      pageInfo:{
        pageSize:20,
        pageNum:1,
        total:0,
        count:true
      }
    }
  },
  methods: {
    jump(){},
    getMessageList(isLoadMore) {
      this.isLoadMore = isLoadMore
      this.loadingVisible = true 
       this.$store.getters.imClient.db().messages.where("groupId").equals(this.groupId).sortBy("sendTime",messages=>{
          var start=messages.length - (this.pageInfo.pageSize * (this.pageInfo.pageNum+1 ) ) 
           if(start<0){
             start=0;
           }
          if(messages ){
            this.messageList=messages.slice( start ,messages.length)
            this.pageInfo.total=messages.length;
            this.pageInfo.pageNum=this.pageInfo.pageNum+1
          }else{
            this.pageInfo.total=0;
          }
           
          this.stringToJson();
        }) 
      this.loadingVisible = false
    },
    getMessageImgWidth(message){
      if(message.sendObject=='I'){
        if(message.sendContent.width){
          return message.sendContent.width
        }
      }
      return 300
    },
    getMessageImgHeight(message){
      if(message.sendObject=='I'){
        if(message.sendContent.height){
          return message.sendContent.height
        }
      }
      return 300
    },
    getAvatarUrl(message) {
      return process.env.BASE_API + '/users/' + message.sendUserid + '/avatar?width=32&height=32'
    },
    getCreateDateTime(message) {
      return util.formatDate.format(new Date(message.sendTime),"yyyy-MM-dd hh:mm:ss")
    },
    showSentMessage(message) {
      this.isLoadMore = false
      if(!message.msgState){
        message.msgState='send'
        message.msgStateDesc="已发送"
      }
      this.messageList.push(message)
      console.log("this.messageList")
      console.log(this.messageList)
    },
    removeMessage(message,index) {
							let msg = {
                msgId:seq.sn(),
								action: 'messageRemoved',
                groupId: message.groupId,
                sourceMsgId:message.msgId,
								toUserid: message.toUserid,
								toUsername:message.toUsername,
								sendUserid:message.sendUserid,
								sendUsername:message.sendUsername,
              }

              if(this.channelGroup.isPrichat==='0') {
                  msg.msgType="group"
              }else{
                msg.msgType="prichat"
              }
							this.$store.getters.imClient.send(msg)
    },
    getToUserid() {
      if(this.channelGroup.isPrichat==='0') {
        return null
      }
      return this.channelGroup.toUserid
    },
    onReconnected() {
      console.log('重连成功！！！')
    },
    onConnectionClosed() {
      console.log('连接被断开')
    },
    onUserOnlineStatusChanged(receiveMessage) {
      for(let message of this.messageList) {
        if(message.sendUserid === receiveMessage.userId) {
          message.senderOnlineStatus = receiveMessage.onlineStatus
        }
      }
    },
    onMessageRemove(receiveMessage) {
      if(this.messageList != null && this.messageList.length > 0) {
        let msgId = receiveMessage.sourceMsgId
        let sendUserid = receiveMessage.sendUserid
        var index = 0
        console.log("在我这里。。。。。。。。。。。。");
        for(let message of this.messageList) {
          if(message.msgId === msgId) {
            message.sendContent="已回撤"
            message.sendObject=""
            this.$set(this.messageList,index,message)
            this.$store.getters.imClient.db().messages.delete(message.msgId);
           // this.messageList.splice(index, 1)
            return
          }
          index++
        }
      }
    },
    onMessageStateReport(receiveMessage) {
      console.log(receiveMessage)
      if(this.messageList != null && this.messageList.length > 0) {
        let msgId = receiveMessage.msgId
        let sourceMsgId = receiveMessage.sourceMsgId
        let msgType=receiveMessage.msgType
        let msgState=receiveMessage.msgState
        let msgStateDesc=receiveMessage.msgStateDesc
         var index=0;
        this.messageList.forEach(i=>{
          if(i.msgId==sourceMsgId){
            i.msgStateDesc=msgStateDesc
            i.msgState=msgState
            this.$set(this.messageList,index,i)
          }
          index++;
        })
      }
    },
    isImage(message) {
      if(message.sendObject!=='I'){
        return false;
      }
      let fileExtension=message.sendContent.fileExtension;
      if(fileExtension==null){
        return false;
      }
      let extension = fileExtension.toLowerCase()
      return extension === 'png' || extension === 'jpeg' || extension === 'jpg'
    },
    isGif(message) {
      if(message.sendObject!=='I'){
        return false;
      }
       let fileExtension=message.sendContent.fileExtension;
      if(fileExtension==null){
        return false;
      }
      let extension = fileExtension.toLowerCase()
      return extension === 'gif'
    },
    getFileUrl(message) {
      return message.sendContent.url
    },
    viewImage(url, width, height) {
      this.image.url = url
      this.image.width = width
      this.image.height = height
      this.$refs.imageViewer.$emit('openDialog')
    },
    stringToJson() {
      for(var i=0;i<this.messageList.length;i++){
        if(this.messageList[i].sendObject=='P'){
          this.messageList[i].sendContent=JSON.parse(this.messageList[i].sendContent);
        }
			}

    },

    onCurrentGroupNewMessage(message) {
				var that = this;
				console.log('chat页面的ononNewMessage方法------------------------') 
        if(message.groupId == this.groupId){ //是这个组的消息
          //放进页面
          console.log("是自己的,存进list")
          this.messageList.push(message)

          if(message.msgType == 'prichat' && message.sendUserid!=this.userInfo.userid){				//私聊 发送状态报告给对方
            //报告收到
            let messageStateReport = {
              action: 'messageStateReport',
              msgType: message.msgType,
              msgState: 'read',
              msgStateDesc: '已读',
              groupId: message.groupId,
              toUserid: message.sendUserid,
              toUsername:message.sendUsername,
              sourceMsgId: message.msgId,
              sendUserid:message.toUserid,
              sendUserid:message.toUsername,
            }
            this.$store.getters.imClient.send(messageStateReport)

          } 

				}else if(message.action == 'messageStateReport'){ //消息报告
					//this.onMessageStateReport(message)
				}else{

				}
      },
      reloadMessage(groupId){
         console.log("监听-----groupId--------" );
        this.$store.getters.imClient.bindCurrentGroupNewMessage(groupId,this.onCurrentGroupNewMessage)
        if(!groupId){
          return;
        } 
        this.pageInfo.pageNum=1;
       this.$store.getters.imClient.db().messages.where("groupId").equals(groupId).sortBy("sendTime",messages=>{
           var start=messages.length-this.pageInfo.pageSize 
           if(start<0){
             start=0;
           }
          if(messages ){
            this.messageList=messages.slice(start,messages.length)
            this.pageInfo.total=messages.length;
          }else{
            this.pageInfo.total=0;
          }
          
          this.stringToJson();
        })
       this.$store.getters.imClient.db().groupMessageState.where("groupId").equals(groupId).modify({unreadMessagesCount:0})
      }
  },
  created() {
    //this.getMessageList(false)
    let imClient = this.$store.getters.imClient
    imClient.bindMessageRemove(this.onMessageRemove)
    imClient.bindHandleMessageStateReport(this.onMessageStateReport)

  },
  watch: {
    groupId: {
      immediate: true, // immediate选项可以开启首次赋值监听
      handler(groupId,oldGroupId) {
        if(groupId!=oldGroupId){
            this.reloadMessage(groupId);

        }
      }
    },
    'messageList': function(newVal, oldVal) {
      // debugger
      this.$nextTick(() => {
        const msgList = document.getElementById('messageList')
        if(!msgList) {
          return
        }
        if(this.messageRemoved) {
          this.messageRemoved = false
          return
        }
        if(this.isLoadMore) {
          const msgContainer = document.getElementById('message_' + oldVal[0].id)
          msgList.scrollTop = msgContainer.offsetTop
          this.isLoadMore = false
        } else {
          msgList.scrollTop = msgList.scrollHeight
        }
      })
    }
  },
  components: { StatusOnlineAvatar, StatusOfflineAvatar, StatusAwayAvatar, StatusDndAvatar,
    ImageViewer: resolve => require(['./imageViewer'], resolve),
  }
}
</script>

<style lang="scss" scoped>
.container {
  overflow-y: auto;
  overflow-x: hidden;
  div {
    font-size: 15px;
  }
  .load-more-message {
    text-align: center;
    font-size: 14px;
    margin: 6px 0 3px 0;
    span {
      color: #1A6CDE;
      cursor: pointer;
    }
  }
  .message-container {
    max-width: 100%;
    width: 100%;
    word-wrap: break-word;
    .message {
      margin: 0 auto;
      padding: 10px 20px 5px 20px;
      width: 100%;
      height:100%;
      position: relative;
      // height: 55px;
    }
  }
  .message-container:hover {
    background-color: #F6F5F4;
  }
  .status-wrapper {
    width: 32px;
    height: 32px;
    line-height: 32px;
    background-color: #DF016E;
    border-radius: 32px;
    text-align: center;
    color: #fff;
    font-weight: bold;
    float: left;
    margin-right: 6px;
    cursor: pointer;
    .status-wrapper-image {
      border-radius: 100%;
      width: 100%;
      height: 100%;
      background-color: #BCB2A6;
    }
    .online-status-container {
      width: 12px;
      height: 12px;
      line-height: 12px;
      margin: -10px 0 0 21px;
    }
  }

    .status-wrapper-right {
    width: 32px;
    height: 32px;
    line-height: 32px;
    background-color: #DF016E;
    border-radius: 32px;
    text-align: center;
    color: #fff;
    font-weight: bold;
    // margin-right: 6px;
    float: right;
    position: relative;
    cursor: pointer;
    .status-wrapper-image {
      border-radius: 100%;
      width: 100%;
      height: 100%;
      background-color: #BCB2A6;
    }
    .online-status-container {
      width: 12px;
      height: 12px;
      line-height: 12px;
      margin: -10px 0 0 21px;
    }
  }


  .sysuser-status-wrapper {
    background-color: #04549C;
  }
  .message-content {
    padding: 0 0 0 35px;
     .sender {
      text-overflow: ellipsis;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      display: inline-block;
    }
    .sender-right {
      text-overflow: ellipsis;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      display: inline-block;
      float: right;
      position: relative;
      right: 5px;
    }
    .info-box{

    }
    .createAt {
      font-size: 12px;
      color: #8F8B86;
      padding: 0 0 0 10px;
      margin-top: -2px;
    }
    .createAt-right {
      font-size: 12px;
      color: #8F8B86;
      padding: 0 0 0 10px;
      margin-top: 2px;
      right: 15px;
      float: right;
      position: relative;
    }
    .content {
      padding: 6px 26px 6px 3px;
      line-height: 25px;
    }
    .content-right {
      padding: 30px 26px 6px 3px;
      line-height: 25px;
      text-align: right;
    }
    .system-content {
      font-size: 14px;
      color: #908C87;
    }
    .content-select {
      padding: 6px 36px 6px 3px;
      line-height: 25px;
      background-color: #F6F5F4;
    }
    .image-file {
      margin-top: 3px;
      max-width: 300px !important;
      max-height: 50px !important;
      cursor: pointer;
    }
    .attach-file {
      margin-top: 3px;
      margin-left: 2px;
      width: 280px;
      height: 64px;
      line-height: 64px;
      vertical-align: middle;
      border: solid 1px #DCDAD6;
      svg {
        float: left;
        border-right: solid 1px #DCDAD6;
      }
      .attach-desc {
        padding-left: 5px;
        width: 205px;
        line-height: 32px;
        color: #464548;
        font-size: 23px;
        float:left;
        div {
          font-size: 13px;
        }
        span {
          font-size: 13px;
          color: #8F8B86;
        }
      }
    }
  }
  .message-content-myself {
    .delete-message {
      color: #1A6CDE;
      cursor: pointer;
      margin-left: 10px;
      font-size: 13px;
      display: none;
      float: right;
      position: relative;
      right:10px;
    }
  }
  .message-content-myself:hover .delete-message {
    display: inline;
  }
  .clear-float {
    clear: both;
  }
}
.my_right {
  float: right;
  margin-top: 30rpx;
  position: relative;
}
	.emptyGif {
	    display: block;
	    width: 100px;
	    height: 100px;
	    /* margin: 0 auto;  //DIV在浏览器中水平居中。布局居中、水平居中， */
	  }


</style>
